package ioc

import (
	"strings"
	"time"

	"gitee.com/zhyclouds/fable-scribe/internal/web"
	"gitee.com/zhyclouds/fable-scribe/internal/web/jwt"
	"gitee.com/zhyclouds/fable-scribe/internal/web/middleware"
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
)

func InitWeb(mdls []gin.HandlerFunc,
	userHdl *web.UserHandler,
	comicHdl *web.ComicHandler) *gin.Engine {

	server := gin.Default()
	server.Use(mdls...)

	userHdl.RegisterRoutes(server)
	comicHdl.RegisterRoutes(server)

	return server
}

func InitGinMiddlewares(jwtHdl jwt.Handler) []gin.HandlerFunc {
	return []gin.HandlerFunc{
		cors.New(cors.Config{
			AllowCredentials: true,
			AllowHeaders:     []string{"Content-Type", "Authorization"},
			ExposeHeaders:    []string{"x-jwt-token", "x-refresh-token"},
			AllowOriginFunc: func(origin string) bool {
				if strings.HasPrefix(origin, "http://localhost") {
					//if strings.Contains(origin, "localhost") {
					return true
				}
				return strings.Contains(origin, "your_company.com")
			},
			MaxAge: 12 * time.Hour,
		}),
		middleware.NewLoginJWTMiddlewareBuilder(jwtHdl).
			IgnorePath("/user/register").
			IgnorePath("/user/login").
			Build(),
	}
}
